<template>
  <el-dialog
      :title="address ? '编辑地址' : '新增地址'"
      v-model="visible"
      width="600px"
      :close-on-click-modal="false"
  >
    <el-form :model="form" ref="formRef" label-width="80px">
      <el-form-item label="收货人" prop="consignee">
        <el-input v-model="form.consignee" placeholder="请输入收货人姓名" />
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="所在地区" prop="area">
        <el-cascader
            v-model="selectedArea"
            :options="areaOptions"
            :props="areaProps"          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="详细地址" prop="streetAddress">
        <el-input
            v-model="form.streetAddress"
            placeholder="请输入详细地址"
            type="textarea"
            :rows="3"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>import * as areaData from 'element-china-area-data'

export default {
  props: {
    value: Boolean,
    address: Object
  },
  data() {
    return {
      form: {
        consignee: '',
        phone: '',
        streetAddress: ''
      },
      selectedArea: [],
      areaOptions: areaData.regionData,
      areaProps: {
        label: 'label',
        value: 'value',
        children: 'children'
      }
    }
  },
  computed: {
    visible: {
      get() { return this.value },
      set(val) { this.$emit('update:modelValue', val) }
    }
  },
  watch: {
    address: {
      immediate: true,
      handler(val) {
        if (val) {
          this.form = { ...val }
          this.selectedArea = [
            val.provinceCode,
            val.cityCode,
            val.districtCode
          ]
        } else {
          this.resetForm()
        }
      }
    }
  },
  methods: {
    resetForm() {
      this.form = {
        consignee: '',
        phone: '',
        streetAddress: ''
      }
      this.selectedArea = []
    },
    async handleSubmit() {
      try {
        const valid = await this.$refs.formRef.validate()
        if (!valid) return

        const addressData = {
          ...this.form,
          provinceCode: this.selectedArea[0],
          cityCode: this.selectedArea[1],
          districtCode: this.selectedArea[2]
        }

        this.$emit('submit', addressData)
        this.visible = false
      } catch (error) {
        console.error('表单验证失败:', error)
      }
    }
  }
}
</script>